<?php


namespace App\Dao;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\User;

class UserDao extends AbstractDao
{
    /**
     * @param array $where
     * @return \Hyperf\Database\Model\Builder|User
     */
    public function where(array $where): \Hyperf\Database\Model\Builder
    {
        $builder = User::query();

        foreach ($where as $field => $value) {
            switch ($field) {
                case 'keywords':
                    $builder->where('id', $value);
                    $builder->orWhere('nickname', 'like', '%' . $value . '%');
                    $builder->orWhere('phone', $value);
                    break;
                default:
                    if (is_array($value)) {
                        $builder->where($field, $value[0], $value[1]);
                    } else {
                        $builder->where($field, $value);
                    }
            }
        }
        return $builder;
    }

    /**
     * @param array $data
     * @return User
     */
    public function create(array $data): User
    {
        $user = $this->first([
            'phone' => $data['phone'],
            'cooperative_id' => $data['cooperative_id']
        ]);
        if ($user) {
            throw new BusinessException(ErrorCode::USER_HAS_EXIST);
        }
        $user = new User();
        $user->fill($data);
        $user->password = password_hash($data['password'], PASSWORD_BCRYPT);
        $user->save();
        return $user;
    }

    /**
     * @param string $data
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|null
     */
    public function filterKeyword(string $data)
    {
        return User::query()
            ->select('id', 'nickname', 'phone', 'avatar', 'alipay as collection_no')
            ->where('phone', '=', $data)
            ->orWhere('nickname', 'like', $data . '%')
            ->first();
    }

}